import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { 
  VALIDATION_ERROR_CODES,
  COMMON_ERROR_CODES
} from '../../utils/errorCodes';

export class NavigationController extends BaseController {
  // 获取场地地图
  async getMap(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { floor } = req.query;

      // 构建查询条件
      const where: any = {};
      if (floor) {
        where.floor = floor;
      }

      // 获取楼层信息
      const floors = await prisma.floor.findMany({
        where,
        orderBy: { level: 'asc' }
      });

      ResponseUtils.success(res, {
        floors
      }, '获取场地地图成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取用户当前位置
  async getUserLocation(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      // 获取用户最新的位置信息
      const location = await prisma.userLocation.findFirst({
        where: { userId },
        orderBy: { createdAt: 'desc' }
      });

      ResponseUtils.success(res, location, '获取用户位置成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新用户位置
  async updateUserLocation(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { latitude, longitude, floor, accuracy } = req.body;

      if (!latitude || !longitude) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '经纬度不能为空');
        return;
      }

      // 验证经纬度范围
      if (latitude < -90 || latitude > 90) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.LATITUDE_OUT_OF_RANGE, '纬度必须在-90到90之间');
        return;
      }

      if (longitude < -180 || longitude > 180) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.LONGITUDE_OUT_OF_RANGE, '经度必须在-180到180之间');
        return;
      }

      // 创建新的位置记录
      const location = await prisma.userLocation.create({
        data: {
          userId,
          latitude: Number(latitude),
          longitude: Number(longitude),
          floor: floor || null,
          accuracy: accuracy ? Number(accuracy) : null
        }
      });

      ResponseUtils.success(res, location, '位置更新成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取导航路线
  async getRoute(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = (req as any).user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, COMMON_ERROR_CODES.UNAUTHORIZED, '用户未登录');
        return;
      }

      const { from, to } = req.query;

      if (!from || !to) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '起点和终点不能为空');
        return;
      }

      // 由于设施功能已移除，暂时返回楼层信息
      // 获取楼层信息作为导航参考
      const floors = await prisma.floor.findMany({
        orderBy: { level: 'asc' }
      });

      // 简化的导航信息
      const route = {
        from: { name: from, type: 'location' },
        to: { name: to, type: 'location' },
        distance: 0,
        estimatedTime: 0,
        floors: floors,
        message: '设施功能已移除，请使用楼层信息进行导航'
      };

      ResponseUtils.success(res, route, '获取导航信息成功（设施功能已移除）');
    } catch (error) {
      next(error);
    }
  }

  // 由于设施功能已移除，以下方法暂时不再使用
  // 如需重新实现导航功能，可以基于楼层信息重新设计
} 